package com.bood.shimmer.common.exception;

import com.alibaba.fastjson.JSONException;
import com.bood.shimmer.common.api.Result;
import com.bood.shimmer.common.enums.BizExceptionEnum;
import com.bood.shimmer.common.enums.ResultEnum;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 全局异常处理器
 * </p>
 *
 * @author：bood
 * @date：2020/9/23
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * <p>
     * com.bood.shimmer.common.handler.BizException
     * </p>
     *
     * @param e: 业务异常
     * @return：com.bood.shimmer.common.api.Result
     * @author：bood
     * @date：2020/9/23
     */
    @ExceptionHandler(BizException.class)
    public Result handleBizException(BizException e) {
        log.error(e.getMessage(), e);
        return Result.res(e.getCode(), null, e.getMessage());
    }

    /**
     * <p>
     * com.bood.shimmer.common.handler.UnauthorizedException
     * </p>
     *
     * @param e: 权限认证异常
     * @return：com.bood.shimmer.common.api.Result
     * @author：bood
     * @date：2020/9/23
     */
    @ExceptionHandler(UnauthorizedException.class)
    public Result handleUnauthorizedException(UnauthorizedException e) {
        log.error(e.getMessage(), e);
        return Result.res(ResultEnum.SIGNATURE_NOT_MATCH.code(), null, e.getMessage());
    }


    /**
     * <p>
     * org.apache.shiro.authz.UnauthenticatedException
     * </p>
     *
     * @param e: org.apache.shiro.authz.UnauthenticatedException
     * @return：com.bood.shimmer.common.api.Result
     * @author：bood
     * @date：2020/9/23
     */
    @ExceptionHandler(UnauthenticatedException.class)
    public Result handleUnauthenticatedException(UnauthenticatedException e) {
        log.error(e.getMessage(), e);
        return Result.res(ResultEnum.SIGNATURE_NOT_MATCH.code(), null, e.getMessage());
    }

    /**
     * <p>
     * org.apache.shiro.authc.AuthenticationException
     * </p>
     *
     * @param e: org.apache.shiro.authc.AuthenticationException
     * @return：com.bood.shimmer.common.api.Result
     * @author：bood
     * @date：2020/9/23
     */
    @ExceptionHandler(AuthenticationException.class)
    public Result handleAuthenticationException(AuthenticationException e) {
        log.error(e.getMessage(), e);
        return Result.res(ResultEnum.SIGNATURE_NOT_MATCH.code(), null, e.getMessage());
    }


    /**
     * <p>
     * org.springframework.web.bind.MethodArgumentNotValidException
     * </p>
     *
     * @param e: org.springframework.web.bind.MethodArgumentNotValidException
     * @return：com.bood.shimmer.common.api.Result
     * @author：bood
     * @date：2020/9/23
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        return Result.res(ResultEnum.BODY_NOT_MATCH.code(), null, e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * <p>
     * org.springframework.validation.BindException
     * </p>
     *
     * @param e: org.springframework.validation.BindException
     * @return：com.bood.shimmer.common.api.Result
     * @author：bood
     * @date：2020/9/23
     */
    @ExceptionHandler(BindException.class)
    public Result handleBindException(HttpServletRequest request, BindException e) {
        Map map = new HashMap<>(16);
        if (e.getBindingResult() != null) {
            List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
            allErrors.stream().filter(Objects::nonNull).forEach(objectError -> {
                map.put("请求路径：" + request.getRequestURI() + "--请求参数：" + (((FieldError) (allErrors.get(0))).getField()), objectError.getDefaultMessage());
            });
        }
        log.error(String.valueOf(map), e);
        return Result.res(ResultEnum.BODY_NOT_MATCH.code(), null, String.valueOf(map));
    }

    /**
     * <p>
     * org.springframework.web.bind.MissingServletRequestParameterException
     * </p>
     *
     * @param e: org.springframework.web.bind.MissingServletRequestParameterException
     * @return：com.bood.shimmer.common.api.Result
     * @author：bood
     * @date：2020/9/23
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error(e.getMessage(), e);
        return Result.res(ResultEnum.BODY_NOT_MATCH.code(), null, e.getMessage());
    }

    /**
     * <p>
     * javax.validation.ValidationException
     * </p>
     *
     * @param e: javax.validation.ValidationException
     * @return：com.bood.shimmer.common.api.Result
     * @author：bood
     * @date：2020/9/23
     */
    @ExceptionHandler(ValidationException.class)
    public Result handleValidationException(ValidationException e) {
        log.error(e.getMessage(), e);
        return Result.res(ResultEnum.BODY_NOT_MATCH.code(), null, e.getCause().getMessage());
    }

    /**
     * <p>
     * javax.validation.ConstraintViolationException
     * </p>
     *
     * @param e: javax.validation.ConstraintViolationException
     * @return：com.bood.shimmer.common.api.Result
     * @author：bood
     * @date：2020/9/23
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result handleConstraintViolationException(ConstraintViolationException e) {
        log.error(e.getMessage(), e);
        return Result.res(ResultEnum.BODY_NOT_MATCH.code(), null, e.getMessage());
    }


    /**
     * <p>
     * java.lang.NullPointerException
     * </p>
     *
     * @param e: 空指针
     * @return：com.bood.shimmer.common.api.Result
     * @author：bood
     * @date：2020/9/23
     */
    @ExceptionHandler(value = NullPointerException.class)
    public Result handleNullPointerException(NullPointerException e) {
        log.error(e.getMessage(), e);
        return Result.res(ResultEnum.BODY_NOT_MATCH.code(), null, e.getMessage());
    }

    /**
     * <p>
     * com.alibaba.fastjson.JSONException
     * </p>
     *
     * @param e: fastjson
     * @return：com.bood.shimmer.common.api.Result
     * @author：bood
     * @date：2020/9/23
     */
    @ExceptionHandler(JSONException.class)
    public Result handleJSONException(JSONException e) {
        log.error(e.getMessage(), e);
        return Result.res(ResultEnum.BODY_NOT_MATCH.code(), null, e.getMessage());
    }

    /**
     * <p>
     * org.springframework.dao.DuplicateKeyException
     * </p>
     *
     * @param e: 主键冲突
     * @return：com.bood.shimmer.common.api.Result
     * @author：bood
     * @date：2020/9/23
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        log.error(e.getMessage(), e);
        return Result.res(BizExceptionEnum.DUPLICATE_KEY.code(), null, BizExceptionEnum.DUPLICATE_KEY.message());
    }

    /**
     * <p>
     * org.springframework.web.servlet.NoHandlerFoundException
     * </p>
     *
     * @param request: org.springframework.web.servlet.NoHandlerFoundException
     * @return：com.bood.shimmer.common.api.Result
     * @author：bood
     * @date：2020/9/23
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handleNoHandlerFoundException(HttpServletRequest request) {
        log.error("接口 [" + request.getRequestURI() + "] 不存在！！！");
        return Result.res(ResultEnum.BODY_NOT_MATCH.code(), null, "接口 [" + request.getRequestURI() + "] 不存在！！！");
    }

    /**
     * <p>
     * java.lang.Exception
     * </p>
     *
     * @param e: Exception
     * @return：com.bood.shimmer.common.api.Result
     * @author：bood
     * @date：2020/9/23
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(HttpServletRequest request, HttpServletResponse response, Exception e) {
        String message;
        if (response instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) response;
            message = String.format("接口 [%s] 出现异常，方法：%s.%s，异常摘要：%s", request.getRequestURI(),
                    handlerMethod.getBean().getClass().getName(), handlerMethod.getMethod().getName(), e.getMessage());
        } else {
            message = e.getMessage();
        }
        log.error(message, e);
        return Result.res(ResultEnum.INTERNAL_SERVER_ERROR.code(), null, message);
    }

}
